package com.iyunsir.lesson02_tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemo02 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;

        // idea try - catch 的快捷键 “Ctrl + Alt + t ”

        try {
            // 1.要知道服务器地址
            InetAddress serverIp = InetAddress.getByName("127.0.0.1");

            // 2.端口号
            int port = 9999;
            socket = new Socket(serverIp,port);

            // 3.发送消息
            os = socket.getOutputStream();

            // 4.读取文件
            FileInputStream fis = new FileInputStream(new File("contact_me_qr.png"));
            // os.write("你好".getBytes());
            // 5.写出文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1){
                os.write(buffer,0,len);
            }

            //通知服务器,我已经结束了
            socket.shutdownOutput(); //我已经传输完

            //确定服务器接收完毕了,才能断开连接
            InputStream inputStream = socket.getInputStream();

            //String byte[]
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer2 = new byte[2014];
            int len2;
            while ((len2 = inputStream.read(buffer2)) != -1){
                baos.write(buffer2,0,len2);
            }
            System.out.println(baos.toString());
            baos.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
